import hashlib
from django.core.mail import EmailMessage
from django.conf import settings
from datetime import datetime


def send_mail(request, user):
    """发送邮件"""
    # 获取当前系统时间
    now = datetime.now()
    timestamp = now.timestamp()
    # 生成数字签名，防止数据在浏览器中传输的过程被篡改
    message = f"u={user.pk}&e=utf8&t={timestamp}&secure=qikux-test"
    # 进行MD5加密
    sign = hashlib.md5(message.encode()).hexdigest()
    url = f"{request.scheme}://{request.get_host()}/active?u={user.pk}&e=utf8&t={timestamp}&sign={sign}"
    body = f"""
                <div style="width: 600px;background-color: aqua;border-radius: 4px;margin: 0 auto;padding: 10px 20px;">
    			<p>尊敬的<b>{user.username}</b>:</p>
    			<p>你在<b>{now.strftime("%Y-%m-%d %H:%M:%S")}</b>注册成功请点击以下链接激活账号</p>
    			<p style="word-break: break-all;">
    				<a href="{url}">{url}</a>
    			</p>
    			<p>本链接有效时间为30分钟，请及时激活</p>
    			<p><b>【欢迎成为我们的一员】</b></p>

    		</div>
            """
    # 发送信息，激活邮箱
    message = EmailMessage(subject="【亿辰】-账号激活", from_email=settings.DEFAULT_FROM_EMAIL, body=body,
                           to=(user.email,))
    # 设置发送内容，支持超文本
    message.content_subtype = "html"
    # 发送邮件
    message.send()
    return url
